package net.ib.mtalk.network.task;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.ContactAccountInfo;
import net.ib.mntalk.protocol.Common.ContactInfo;
import net.ib.mntalk.protocol.Common.Name;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.AddContactsReq;
import net.ib.mntalk.protocol.Session.AddContactsRes;
import net.ib.mntalk.protocol.Session.GetBuddyInfosReq;
import net.ib.mntalk.protocol.Session.GetContactsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.database.helper.ContactDatabaseHelper;
import net.ib.mtalk.database.helper.GroupDatabaseHelper;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.sync.ContactComparator;
import net.ib.mtalk.ui.buddy.talk.BuddyTalkListActivity;
import net.ib.mtalk.ui.favorite.FavoriteActivity;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.NotifyingAsyncQueryHandler;

public class AllAddContactsTask extends AsyncNetTask {
	
	private AddContactsReq mAddContactsReq;
	
	public static String PHONE_NAME = StructuredName.CONTENT_ITEM_TYPE;
	public static String ACCOUNT_MNTALK = "";
	public static String ACCOUNT_FACEBOOK = "vnd.android.cursor.item/vnd.facebook.profile";
	public static String ACCOUNT_TWITTER = "vnd.android.cursor.item/vnd.twitter.profile";
	public static String ACCOUNT_EMAIL = Email.CONTENT_ITEM_TYPE;
	public static String ACCOUNT_PHONE = Phone.CONTENT_ITEM_TYPE;
	private Map<String, String> map = new HashMap<String, String>();
	private Map<String, Integer> map_version = new HashMap<String, Integer>();
	
	public AllAddContactsTask(Context _context, Handler _uiHandler) {
		super(_context, _uiHandler);
		mContext = _context;
		mUiHandler = _uiHandler;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		String raw_contact = null;
		
		String mimeType = null;
		String family_name = null;
		String given_name = null;
		String middle_name = null;
		String phonetic_family_name = null;
		String phonetic_given_name = null;
		String phonetic_middle_name = null;
		String prefix = null;
		String suffix = null;
		String displayname = null;
		ContactAccountInfo contactAccountInfo = null;
		mAddContactsReq = new AddContactsReq();
		
		Cursor cursor = mContext.getContentResolver().query(Data.CONTENT_URI, 
														new String[]{Data._ID, Data.MIMETYPE, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5, Data.DATA6, 
														Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA1, Data.RAW_CONTACT_ID}, null, null, Data._ID);
		try{
			while (cursor.moveToNext()) {
				mimeType = cursor.getString(cursor.getColumnIndexOrThrow(Data.MIMETYPE));
				if(mimeType.equals(PHONE_NAME)){
					family_name 		 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.FAMILY_NAME));
					given_name			 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.GIVEN_NAME));
					middle_name 		 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.MIDDLE_NAME));
					phonetic_family_name = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.PHONETIC_FAMILY_NAME));
					phonetic_given_name  = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.PHONETIC_GIVEN_NAME));
					phonetic_middle_name = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.PHONETIC_MIDDLE_NAME));
					prefix				 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.PREFIX));
					suffix				 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.SUFFIX));
					displayname			 = cursor.getString(cursor.getColumnIndexOrThrow(StructuredName.DISPLAY_NAME));
					raw_contact			 = cursor.getString(cursor.getColumnIndexOrThrow(Data.RAW_CONTACT_ID));
					
					if(family_name == null) family_name = "";
					if(given_name == null) given_name = "";
					if(middle_name == null) middle_name = "";
					if(phonetic_family_name == null) phonetic_family_name = "";
					if(phonetic_given_name == null) phonetic_given_name = "";
					if(phonetic_middle_name == null) phonetic_middle_name = "";
					if(prefix == null) prefix = "";
					if(suffix == null) suffix = "";
					if(displayname == null) displayname = "";
					
					Name name = new Common.Name().setFirstName(given_name).setLastName(family_name).setMiddleName(middle_name)
					.setNamePrefix(prefix).setNameSuffix(suffix)
					.setPhoneticFamilyName(phonetic_family_name).setPhoneticGivenName(phonetic_given_name).setPhoneticMiddleName(phonetic_middle_name);
					
//					Cursor cursor3 = mContext.getContentResolver().query(RawContacts.CONTENT_URI, null, RawContacts.DELETED + "='0' AND " + RawContacts._ID + "=?",
//							new String[]{raw_contact}, null);
//					if(cursor3.getCount() != 0){	// 지워진 폰은 올리지 않음
					Cursor cursor2 = mContext.getContentResolver().query(Phone.CONTENT_URI, 
								new String[]{Phone.NUMBER, Phone.RAW_CONTACT_ID, Phone.DATA_VERSION}, Data.RAW_CONTACT_ID + "=?", new String[]{raw_contact}, null);
					try{
						while(cursor2.moveToNext()){
//								mimeType = cursor2.getString(cursor.getColumnIndexOrThrow(Data.MIMETYPE));
//								if(mimeType.equals(ACCOUNT_PHONE)){
							contactAccountInfo = new Common.ContactAccountInfo().setAccountValue(cursor2.getString(cursor2.getColumnIndexOrThrow(Phone.NUMBER)))	 
												.setType(Common.Phone);
									// 폰만 올림.
									/*					} else if(mimeType.equals(ACCOUNT_EMAIL)){
						contactAccountInfo = new Common.ContactAccountInfo().setAccountValue(cursor2.getString(cursor2.getColumnIndexOrThrow(Data.DATA1)))
												.setType(Common.Email);
					} else if(mimeType.equals(ACCOUNT_TWITTER)){
						contactAccountInfo = new Common.ContactAccountInfo().setAccountValue(cursor2.getString(cursor2.getColumnIndexOrThrow(Data.DATA1)))
												.setType(Common.Twitter);
					} else if(mimeType.equals(ACCOUNT_FACEBOOK)){
						contactAccountInfo = new Common.ContactAccountInfo().setAccountValue(cursor2.getString(cursor2.getColumnIndexOrThrow(Data.DATA1)))
												.setType(Common.Facebook);
					} else if(mimeType.equals(ACCOUNT_MNTALK)){
						contactAccountInfo = new Common.ContactAccountInfo().setAccountValue(cursor2.getString(cursor2.getColumnIndexOrThrow(Data.DATA1)))
												.setType(Common.MnTalkID);
									 */	//				} else continue;
							addContactRequest(contactAccountInfo, name);
							map.put(raw_contact, displayname);
							map_version.put(raw_contact, cursor2.getInt(cursor2.getColumnIndexOrThrow(Phone.DATA_VERSION)));
						}
					} finally{
						cursor2.close();
					}
//					}
				}
			}
		} finally{
			cursor.close();
		}
		
		MTalkLogWriter.d(mAddContactsReq.getContactCount() + "  개 추가");
		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mAddContactsReq)
			.setMethodId(MethodId.Session.Contact.AddContacts)
			.build();
		return rev;
	}

	private void addContactRequest(ContactAccountInfo contactAccountInfo,
			Name name) {
		ContactInfo contactInfo = new Common.ContactInfo().setAccount(contactAccountInfo).setName(name);
		mAddContactsReq.addContact(contactInfo);
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,	Object receivedObject) {
		MTalkLogWriter.d("AddContactsTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		AddContactsRes addContactsRes = (AddContactsRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("AddContactsTask ResponseCode : " + addContactsRes.getResponseCode());
		
		if(addContactsRes.getResponseCode() == Common.SUCCESS){
//			GroupDatabaseHelper.insert(mContext);
			ContactDatabaseHelper.insert(mContext, mAddContactsReq, map, map_version);
			// ContactsVersion 저장
//			GlobalPreferences.setContact_Version(ContactComparator.checkContactVersion());
			getAllBuddies();
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ALL_ADD_CONTACTS_SUCCESS));
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ALL_ADD_CONTACTS_FAIL));
		}
	}
	
	private void getAllBuddies(){
		GetBuddyInfosReq getBuddyInfosReq = new GetBuddyInfosReq();
		getBuddyInfosReq.setPredicate(new Common.UUIDSlicePredicate().setSliceRange((new Common.UUIDSliceRange().setAscending(true).setMaxCount(GetBuddyInfosTask.GET_BUDDY_MAX_COUNT))));
		getBuddyInfosReq.addProperty(Common.USER_PROPERTY_NAME).addProperty(Common.USER_PROPERTY_PROFILE_IMAGE).addProperty(Common.USER_PROPERTY_STATUS).addProperty(Common.USER_PROPERTY_BIRTHDAY);
//		getBuddyInfosReq.addProperty(Common.BUDDY_SEPARATOR);
		
		GetBuddyInfosTask task = new GetBuddyInfosTask(mContext, mUiHandler, getBuddyInfosReq);
		task.execute();
	}
}
